package com.meowcook.service.impl;

import com.meowcook.exception.AppException;
import com.meowcook.common.AppResult;
import com.meowcook.common.ResultCode;
import com.meowcook.dao.CommentMapper;
import com.meowcook.dao.RecipeMapper;
import com.meowcook.mapper.CommentPojoMapper;
import com.meowcook.pojo.dto.CommentDTO;
import com.meowcook.pojo.dto.CommentListDTO;
import com.meowcook.pojo.po.Comment;
import com.meowcook.pojo.po.Recipe;
import com.meowcook.pojo.vo.CommentVO;
import com.meowcook.service.ICommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28792
 * Date: 2025-05-17
 * Time: 16:34
 */
@Slf4j
@Service
public class CommentService implements ICommentService {
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private CommentPojoMapper commentPojoMapper;
    @Resource
    private RecipeMapper recipeMapper;
    @Override
    public void addComment(CommentDTO commentDTO) {
        // 数据转化
        Comment comment = commentPojoMapper.toPO(commentDTO);
        // 设置默认值
        comment.setLikeCount(0);
        comment.setReplyCount(0);
        comment.setIsTop((byte) 0);
        comment.setIsApproved((byte) 1);
        comment.setIsDeleted((byte) 0);
        Date date = new Date();
        comment.setCreateTime(date);
        comment.setUpdateTime(date);
        // 调用dao
        int row = commentMapper.insertSelective(comment);
        if (row != 1) {
            log.info("新增评论comment失败");
            throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        }
        // 同步Recipe评论数
        Recipe recipe = recipeMapper.selectByPrimaryKey(comment.getRecipeId());
        Recipe updateRecipe = new Recipe();
        updateRecipe.setId(comment.getRecipeId());
        updateRecipe.setCommentCount(recipe.getCommentCount() + 1);
        int row2 = recipeMapper.updateByPrimaryKeySelective(updateRecipe);
        if (row2 != 1) {
            log.info("更新Recipe评论数失败");
            throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        }
    }

    @Override
    public List<CommentVO> getCommentList(CommentListDTO commentListDTO) {
        List<Comment> comments = commentMapper.selectByRecipeId(commentListDTO);
        return commentPojoMapper.toVO(comments);
    }
}
